"""
Copyright (c) 2008, Luke Freeman
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

   * Redistributions of source code must retain the above copyright notice, this 
     list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice, this 
     list of conditions and the following disclaimer in the documentation and/or 
     other materials provided with the distribution.
   * Neither the name of Flag-Up nor the names of its contributors may 
     be used to endorse or promote products derived from this software without specific 
     prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
"""


from config.configuration import *
from ui.glade.preferences_dialog import PreferencesDialog
from ui.glade.about_dialog import AboutDialog
from ui.notification import *
from ui.glade.new_mail_dialog import *

import time
import sys

import pygtk, gtk, gtk.glade
import gobject

from base.singleton import *

class StatusIcon(gtk.StatusIcon):

    # constants
    STATUS_CHECK_UNREAD = 1
    STATUS_CHECK_NONE = 0
    STATUS_CHECK_ERROR = -1  
    STATUS_NEEDS_CONFIG = -2

    __config = Configuration()

    def __init__(self):
        gtk.StatusIcon.__init__(self)
        
        self.update_icon(StatusIcon.STATUS_CHECK_NONE)
        self.connect('popup-menu', self.on_status_icon_right_click)
        self.connect('activate', self.on_status_icon_left_click)

        self.pref_dialog = PreferencesDialog(self)
        self.about_dialog = AboutDialog()
        
        if self.__config.is_configured is not True:
            gobject.idle_add(self.show_initial_notification)
        else:
            status = StatusIcon.STATUS_CHECK_UNREAD
            if status == StatusIcon.STATUS_CHECK_UNREAD:
                gobject.idle_add(self.show_new_mail_notification)
        
    

    def show_initial_notification(self):
        icon = gtk.image_new_from_file('ui/icons/48/welcome-smiley.png').get_pixbuf()
        welcome_message = "Hey there! Welcome to <b>Flag-Up</b>. The Flag-Up main icon will tell " \
                          "you your mail status.\n\nTo get started " \
                          "you will need to set up your mail accounts. Please click on the " \
                          "<b>View Preferences</b> button " \
                          "below.\n\nOh .. and thank you!"

        MailNotification(self, "Welcome!", welcome_message, icon, 50000, "view_pref").show()

        return False  


    def show_new_mail_notification(self):
        #message = "You have <b>5</b> new mail message(s).\n\n"
        #message += "<span size='small'>testing ....</span>\n\n"
        #message += "Please 'Right Click' the status icon to see your messages."
        #MailNotification(self, "You Have New Mail!", message, None, 50000, "view_mail").show()
		x = NewMailNotification()
		x.show()        


    def create_popup_menu(self):
        popup_menu = gtk.Menu()

        check_mail_item = gtk.ImageMenuItem("Check for new mail")
        check_mail_item.set_image(gtk.image_new_from_file('ui/icons/16/gnome-mail-send-receive.png'))
        check_mail_item.connect("activate", self.on_check_mail_item_activate)
        check_mail_item.show()
        popup_menu.append(check_mail_item)

        preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        preferences_item.connect("activate", self.on_preferences_item_activate)
        preferences_item.show()
        popup_menu.append(preferences_item)        

        separator = gtk.SeparatorMenuItem()
        separator.show()
        popup_menu.append(separator)

        # add mail summaries
        no_mail_item = gtk.ImageMenuItem("No New Mail ..")
        no_mail_item.show()
        popup_menu.append(no_mail_item)        



        separator = gtk.SeparatorMenuItem()
        separator.show()
        popup_menu.append(separator)

        about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about_item.connect("activate", self.on_about_item_activate)
        about_item.show()
        popup_menu.append(about_item)    


        quit_item = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        quit_item.connect("activate", self.on_quit_item_activate)
        quit_item.show()
        popup_menu.append(quit_item)    

        return popup_menu

    def blink_for_duration(self, duration):
        self.set_blinking(True)
        if (duration) >= 0:
            gobject.timeout_add(duration * 1000, self.set_blinking, False)
      

    def update_icon(self, status):
        icon_path_format = "ui/icons/%(icon_name)s.png"

        if status == StatusIcon.STATUS_CHECK_UNREAD:
            tooltip_text = 'You have unread email'
            #icon_name = 'gnome-mail-unread'
            icon_name = 'mail-up-48'
        elif status == StatusIcon.STATUS_CHECK_NONE:
            tooltip_text = 'You have no new messages'
            icon_name = 'gnome-mail-envelope'      
        elif status == StatusIcon.STATUS_CHECK_ERROR:
            tooltip_text = 'An error occurred checking your mail'
            icon_name = 'gnome-dialog-warning'
        elif status == StatusIcon.STATUS_NEEDS_CONFIG:
            tooltip_text = 'Flag-Up has not yet been configured for any mail accounts'
            icon_name = '48/gnome-mail-warning'    
        else:
            raise Exception("An invalid status was set [code = %d]" % status)

        self.set_tooltip(tooltip_text)
        icon_path = icon_path_format % { 'icon_name' : icon_name }

        self.set_tooltip(tooltip_text)
        self.set_from_file(icon_path)


        # flashing? if so, set duration
        if status == StatusIcon.STATUS_CHECK_UNREAD:
            do_flash = self.__config.get_value("/flash/do")
            if (do_flash):
                fixed = self.__config.get_value("/flash/fixed")
                fixed_interval = self.__config.get_value("/flash/fixed_interval")
                duration = fixed_interval if fixed else -1
                self.blink_for_duration(duration)
                
        elif status != StatusIcon.STATUS_CHECK_NONE:
            self.blink_for_duration(-1)        
    

    # event handlers -----
    # status icon handlers
    def on_status_icon_right_click(self, data, event_button, event_time):
        menu = self.create_popup_menu()
        menu.popup(None, None, None, event_button, event_time)

        
    def on_status_icon_left_click(self, event):
		pass
  

    # popup menu handlers
    def on_about_item_activate(self, event):
        self.about_dialog.show()

    def on_quit_item_activate(self, event):  
        sys.exit(1)

    def on_preferences_item_activate(self, event):   
        self.pref_dialog.show()

    def on_check_mail_item_activate(self, event):   
        self.update_icon(StatusIcon.STATUS_CHECK_UNREAD)
        gobject.idle_add(self.show_new_mail_notification)


